package com.ope.quartz.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.convert.Convert;
import cn.hutool.core.io.FileUtil;
import com.ope.common.utils.*;
import com.ope.quartz.mapper.GuaranteeMapper;
import com.ope.quartz.service.IGuanateeService;
import com.ope.quartz.task.FileHandleConstant;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.FileUtils;
import org.quartz.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.io.*;
import java.net.InetAddress;
import java.text.SimpleDateFormat;
import java.util.*;

import java.util.regex.Pattern;
import java.util.regex.Matcher;
import java.util.stream.Collectors;

/**
 * 定时任务调度信息 服务层
 * 
 * @author gnrx
 */
@Service
@Slf4j
public class GuanateeServiceImpl implements IGuanateeService {
    @Autowired
    private GuaranteeMapper guaranteeMapper;


    @Value("${file.path}")
    private String path;
    @Value("${phone}")
    private String phone;
    @Value("${networks.masterip}")
    private String masterip;
    @Value("${networks.slaveip}")
    private String slaveip;
    @Value("${checkfiles.path}")
    private String checkFilePath;


    @Override
    public void reportAlarmData(String time) throws Exception {
        if (!time.endsWith(":00")) {
            //为避免定时任务延迟，如果时间的秒数不为0强制设置为0
            time = time.substring(0, time.length() - 3) + ":00";
        }
        List<ReportAlarmInfo> infoList = new ArrayList<>();
        List<ReportAlarmConfig> reportAlarmConfigList = guaranteeMapper.getConfigInfo();
        log.info("数据库读取配置******" + reportAlarmConfigList.size());
        if (reportAlarmConfigList.size() == 0) {
            log.info("E_ALARM_CONFIG表中status=0的数据条数为0，定时任务终止");
        } else {
            for (ReportAlarmConfig config : reportAlarmConfigList) {
                String fileCronExpression = config.getFileCronExpression();
                Integer delaySecond = config.getDelaySecond();
                String time1 = DateUtils.secondAdd(time, delaySecond * -1, DateUtils.FORMAT_STR1);
                CronExpression cronExpression = new CronExpression(fileCronExpression);
                SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                boolean res = cronExpression.isSatisfiedBy(format.parse(time1));
                log.info("resresresres******" + res);
                if (!res) {
                    log.info(time1 + "不满足时间表达式" + fileCronExpression + "忽略本次判定");
                    continue;
                }
                //获取监控的文件目录,创建备份目录
                String fileDir = config.getFileDir();
                File file = new File(fileDir);
                String fileName = file.getName();
                String bkFileName = fileName + "_alarm";
                String parentPath = file.getParent();
                String bkFilePath = parentPath + File.separator + bkFileName;
                File bkFile = new File(bkFilePath);
                if (!bkFile.exists()) {
                    bkFile.mkdir();
                }
                //如果是0点整的，则清空7天前的文件，放到备份目录
                if (time.contains("00:00:00")) {
                    String preTime = DateUtils.dayAdd(time, -7, DateUtils.FORMAT_STR1);
                    long preTimestamp = DateUtils.dateStringToLong(preTime, DateUtils.FORMAT_STR1);
                    Collection<File> files = FileUtils.listFiles(file, null, false);
                    for (File f : files) {
                        long l = f.lastModified();
                        if (l < preTimestamp * 1000) {
                            //将文件移动到本分目录
                            FileUtils.moveFileToDirectory(f, bkFile, true);
                        }
                    }
                }
                //提取文件名称表达式
                String nameExpression = config.getFileNameExpression();
                String[] parterns = this.extract(nameExpression);
                String fileName1 = nameExpression;
                log.info("fileName1fileName1fileName1fileName1******" + fileName1);
                if (parterns.length > 0) {
                    for (int i = 0; i < parterns.length; i++) {
                        String partern = parterns[i];
                        String tmpPartern = partern.replace("{", "").replace("}", "");
                        if (i == 0) {
                            String timrStr = DateUtils.dateFormat(time1, DateUtils.FORMAT_STR1, tmpPartern);
                            fileName1 = nameExpression.replace("{" + partern + "}", timrStr);
                        } else {
                            //表示文件名称中是一个时间范围
                            if (partern.contains("+") || partern.contains("-")) {
                                //表示后续时间点与前第一个时间点有对应关系
                                String timeStr1 = "";

                                if (partern.contains("+")) {
                                    String[] strs = partern.split("\\+");
                                    //获取第二个值
                                    int min = Integer.valueOf(strs[1]);
                                    timeStr1 = DateUtils.minuteAdd(time1, min, DateUtils.FORMAT_STR1);
                                    timeStr1 = DateUtils.dateFormat(timeStr1, DateUtils.FORMAT_STR1, strs[0]);
                                } else {
                                    String[] strs = partern.split("-");
                                    int min = Integer.valueOf(strs[1]);
                                    timeStr1 = DateUtils.minuteAdd(time1, min * (-1), DateUtils.FORMAT_STR1);
                                    timeStr1 = DateUtils.dateFormat(timeStr1, DateUtils.FORMAT_STR1, strs[0]);
                                }

                                fileName1 = fileName1.replace("{" + partern + "}", timeStr1);
                                log.info(fileName1);
                            }
                        }
                    }
                }

                //获取所有文件
                Collection<File> files = FileUtils.listFiles(file.getAbsoluteFile(), null, false);
                log.info("filesfilesfilesfilesfiles******" + files.size());
                boolean flag = true;
                for (File f : files) {
                    String fileName2 = f.getName();
                    if (fileName2.equals(fileName1)) {
                        //表示该文件在此目录
                        flag = false;
                        break;
                    }
                }
                if (flag) {
                    ReportAlarmInfo reportAlarmInfo = new ReportAlarmInfo();
                    reportAlarmInfo.setAlarmConfigId(config.getId());
                    reportAlarmInfo.setAlarmInfo("发送华东" + fileName1 + "失败");
                    reportAlarmInfo.setAlarmTime(time1);
                    reportAlarmInfo.setAlarmFileName(fileName1);
                    reportAlarmInfo.setCreateTime(time);
                    infoList.add(reportAlarmInfo);

                }


            }
        }
        log.info("infoListinfoListinfoListinfoList******" + infoList.size());
        if (infoList.size() > 0) {
            this.createFile(time, infoList);
            guaranteeMapper.batchInsertAlarmInfo(infoList);
        }
    }

    @Override
    public void dqGuaranteePlant(String date, Integer apm) throws Exception {
        log.info("dqGuaranteePlant短期文件扫描任务" + date + "******" + apm);
        InetAddress inetAddress = InetAddress.getLocalHost();
        log.info("inetAddressinetAddressinetAddress******" +  inetAddress);
//        String mechingeHost = "10.31.48.176";
//        String serverHost = "10.31.48.176";
        int serverPort = 9110;
        Boolean masterStatus = getAliveStatus(masterip, masterip, serverPort);
        log.info("masterStatusmasterStatusmasterStatus******" +  masterStatus);
//        String slaveMechingeHost = "10.31.48.176";
//        String slaveServerHost = "10.31.48.176";
        int slaveServerPort = 9110;
        Boolean slaveStatus = getAliveStatus(slaveip, slaveip, slaveServerPort);
        log.info("slaveStatusslaveStatusslaveStatus******" +  slaveStatus);
        //获取静态内部类中状态中为1的数据---上午短期发送文件校验
        List<FileConfig> fileConfigs =  getlist();
        List<FileConfig> nameParterns =
                fileConfigs.stream().filter(e -> e.getStatus() == apm).collect(Collectors.toList());
        if (masterStatus && inetAddress.getHostAddress().equals(masterip)) {
            log.info("走主机主机主机开始校验文件******" +  new Date());
            handlerFileLogic(date, nameParterns);
        } else {
            //从机处理
            log.info("走从机从机从机开始校验文件******" +  new Date());
            handlerFileLogic(date, nameParterns);
        }
        log.info("结束结束结束结束结束结束******" +  apm);
    }

    /**
     * @Date 2024年3月13日08:47:14
     * @return   List<FileConfig>  List<FileConfig>
     * @Author fxr
     */
    private List<FileConfig> getlist() {
        List<FileConfig> fileConfigList = new ArrayList<>();
        //短期上午一次
//        fileConfigList.add(new FileConfig("1",
//                "上海光伏短期功率预测{yyyyMMdd+1440}-{yyyyMMdd+14400}.RB",
//                "0 0 9 * * ?", "/home/sprixin/shanghai/hdjhcRB/dq/",
//                "/home/sprixin/shanghai/hdjhcRB/bak/", 1));
        //短期上午一次
        fileConfigList.add(new FileConfig("1",
                FileHandleConstant.shdqsolarcaprbrule,
                "0 0 9 * * ?", FileHandleConstant.shdqsolarcaprb,
                FileHandleConstant.shdqsolarcaprbbak, 1));
        fileConfigList.add(new FileConfig("2",FileHandleConstant.shdqwindcaprbrule,
                "0 0 9 * * ?", FileHandleConstant.shdqwindcaprb,
                FileHandleConstant.shdqwindcaprbbak, 1));
        fileConfigList.add(new FileConfig("3",FileHandleConstant.shsolarrbrule,
                "0 0 9 * * ?", FileHandleConstant.shsolarrb,
                FileHandleConstant.shsolarrbbak,1));
        fileConfigList.add(new FileConfig("4",FileHandleConstant.shsolarehrule,
                "0 0 9 * * ?", FileHandleConstant.shsolareh,
                FileHandleConstant.shsolarehbak,1));
        fileConfigList.add(new FileConfig("5",FileHandleConstant.shwindrbrule,
                "0 0 9 * * ?", FileHandleConstant.shwindrb,
                FileHandleConstant.shwindrbbak,1));
        fileConfigList.add(new FileConfig("6",FileHandleConstant.shwindehrule,
                "0 0 9 * * ?", FileHandleConstant.shwindeh,
                FileHandleConstant.shwindehbak,1));
        fileConfigList.add(new FileConfig("7",FileHandleConstant.shddsolarrbrule,
                "0 0 9 * * ?", FileHandleConstant.shddsolarrb,
                FileHandleConstant.shddsolarrbbak,1));
        fileConfigList.add(new FileConfig("8",FileHandleConstant.shddsolarehrule,
                "0 0 9 * * ?", FileHandleConstant.shddsolareh,
                FileHandleConstant.shddsolarehbak,1));
        fileConfigList.add(new FileConfig("9",FileHandleConstant.shddwindrbrule,
                "0 0 9 * * ?", FileHandleConstant.shddwindrb,
                FileHandleConstant.shddwindrbbak,1));
        fileConfigList.add(new FileConfig("10",FileHandleConstant.shddwindehrule,
                "0 0 9 * * ?", FileHandleConstant.shddwindeh,
                FileHandleConstant.shddwindehbak,1));
        fileConfigList.add(new FileConfig("11",FileHandleConstant.shseawindrbrule,
                "0 0 9 * * ?", FileHandleConstant.shseawindrb,
                FileHandleConstant.shseawindrbbak,1));
        fileConfigList.add(new FileConfig("12",FileHandleConstant.shseawindehrule,
                "0 0 9 * * ?", FileHandleConstant.shseawindeh,
                FileHandleConstant.shseawindehbak,1));
//        fileConfigList.add(new FileConfig("13",FileHandleConstant.shdqeflrule,
//                    "0 0 9 * * ?", FileHandleConstant.shdqefl,
//                FileHandleConstant.shdqeflbak,1));
        fileConfigList.add(new FileConfig("14",FileHandleConstant.shqkjxnyxmlrule,
                "0 0 9 * * ?", FileHandleConstant.shqkjxnyxml,
                FileHandleConstant.shqkjxnyxmlbak,1));
        fileConfigList.add(new FileConfig("15",FileHandleConstant.shqkjsolarxmlrule,
                "0 0 9 * * ?", FileHandleConstant.shqkjsolarxml,
                FileHandleConstant.shqkjsolarxmlbak,1));
//        fileConfigList.add(new FileConfig("16",FileHandleConstant.shjzssolarxmlrule,
//                    "0 0 9 * * ?", FileHandleConstant.shjzssolarxml,
//                FileHandleConstant.shjzssolarxmlbak,1));
        fileConfigList.add(new FileConfig("17",FileHandleConstant.shjzswindxmlrule,
                "0 0 9 * * ?", FileHandleConstant.shjzswindxml,
                FileHandleConstant.shjzswindxmlbak,1));
//        fileConfigList.add(new FileConfig("18",FileHandleConstant.shfbsxmlrule,
//                    "0 0 9 * * ?", FileHandleConstant.shfbsxml,
//                FileHandleConstant.shfbsxmlbak,1));
//        fileConfigList.add(new FileConfig("19",FileHandleConstant.shddsolarxmlrule,
//                    "0 0 9 * * ?", FileHandleConstant.shddsolarxml,
//                FileHandleConstant.shddsolarxmlbak,1));
//        fileConfigList.add(new FileConfig("20",FileHandleConstant.shczxmlrule,
//                    "0 0 9 * * ?", FileHandleConstant.shczxml,
//                FileHandleConstant.shczxmlbak,1));
        fileConfigList.add(new FileConfig("21",FileHandleConstant.shbalancetxtrule,
                "0 0 9 * * ?", FileHandleConstant.shbalancetxt,
                FileHandleConstant.shbalancetxtbak,1));
        fileConfigList.add(new FileConfig("22",FileHandleConstant.shbalanceehrule,
                "0 0 9 * * ?", FileHandleConstant.shbalanceeh,
                FileHandleConstant.shbalanceehbak,1));
        //短期下午二次
        fileConfigList.add(new FileConfig("23",FileHandleConstant.shsolarpmrbrule,
                "0 0 9 * * ?", FileHandleConstant.shsolarpmrb,
                FileHandleConstant.shsolarpmrbbak,2));
        fileConfigList.add(new FileConfig("24",FileHandleConstant.shsolarpmehrule,
                "0 0 9 * * ?", FileHandleConstant.shsolarpmeh,
                FileHandleConstant.shsolarpmehbak,2));
        fileConfigList.add(new FileConfig("25",FileHandleConstant.shwindpmrbrule,
                "0 0 9 * * ?", FileHandleConstant.shwindpmrb,
                FileHandleConstant.shwindpmrbbak,2));
        fileConfigList.add(new FileConfig("26",FileHandleConstant.shwindpmehrule,
                "0 0 9 * * ?", FileHandleConstant.shwindpmeh,
                FileHandleConstant.shwindpmehbak,2));
        fileConfigList.add(new FileConfig("27",FileHandleConstant.shddsolarpmrbrule,
                "0 0 9 * * ?", FileHandleConstant.shddsolarpmrb,
                FileHandleConstant.shddsolarpmrbbak,2));
        fileConfigList.add(new FileConfig("28",FileHandleConstant.shddsolarpmehrule,
                "0 0 9 * * ?", FileHandleConstant.shddsolarpmeh,
                FileHandleConstant.shddsolarpmehbak,2));
        fileConfigList.add(new FileConfig("29",FileHandleConstant.shddwindpmrbrule,
                "0 0 9 * * ?", FileHandleConstant.shddwindpmrb,
                FileHandleConstant.shddwindpmrbbak,2));
        fileConfigList.add(new FileConfig("30",FileHandleConstant.shddwindpmehrule,
                "0 0 9 * * ?", FileHandleConstant.shddwindpmeh,
                FileHandleConstant.shddwindpmehbak,2));
        fileConfigList.add(new FileConfig("31",FileHandleConstant.shseawindpmrbrule,
                "0 0 9 * * ?", FileHandleConstant.shseawindpmrb,
                FileHandleConstant.shseawindpmrbbak,2));
        fileConfigList.add(new FileConfig("32",FileHandleConstant.shseawindpmehrule,
                "0 0 9 * * ?", FileHandleConstant.shseawindpmeh,
                FileHandleConstant.shseawindpmehbak,2));

        fileConfigList.add(new FileConfig("33",FileHandleConstant.shqkjxnyxmlpmrule,
                "0 0 9 * * ?", FileHandleConstant.shqkjxnyxmlpm,
                FileHandleConstant.shqkjxnyxmlpmbak,2));
        fileConfigList.add(new FileConfig("34",FileHandleConstant.shqkjsolarxmlpmrule,
                "0 0 9 * * ?", FileHandleConstant.shqkjsolarxmlpm,
                FileHandleConstant.shqkjsolarxmlpmbak,2));
//        fileConfigList.add(new FileConfig("35",FileHandleConstant.shjzssolarxmlpmrule,
//                "0 0 9 * * ?", FileHandleConstant.shjzssolarxmlpm,
//                FileHandleConstant.shjzssolarxmlpmbak,2));
        fileConfigList.add(new FileConfig("36",FileHandleConstant.shjzswindxmlpmrule,
                "0 0 9 * * ?", FileHandleConstant.shjzswindxmlpm,
                FileHandleConstant.shjzswindxmlpmbak,2));
//        fileConfigList.add(new FileConfig("37",FileHandleConstant.shfbsxmlpmrule,
//                "0 0 9 * * ?", FileHandleConstant.shfbsxmlpm,
//                FileHandleConstant.shfbsxmlpmbak,2));
//        fileConfigList.add(new FileConfig("38",FileHandleConstant.shddsolarxmlpmrule,
//                "0 0 9 * * ?", FileHandleConstant.shddsolarxmlpm,
//                FileHandleConstant.shddsolarxmlpmbak,2));
//        fileConfigList.add(new FileConfig("39",FileHandleConstant.shczxmlpmrule,
//                "0 0 9 * * ?", FileHandleConstant.shczxmlpm,
//                FileHandleConstant.shczxmlbakpm,2));
        //超短期
        fileConfigList.add(new FileConfig("40",FileHandleConstant.shcdqforetxtrule,
                "0 0 9 * * ?", FileHandleConstant.shcdqforetxt,
                FileHandleConstant.shcdqforetxtbak,3));
        fileConfigList.add(new FileConfig("41",FileHandleConstant.shcdqforeehrule,
                "0 0 9 * * ?", FileHandleConstant.shcdqforeeh,
                FileHandleConstant.shcdqforeehbak,3));
        fileConfigList.add(new FileConfig("42",FileHandleConstant.shcdqyctxtrule,
                "0 0 9 * * ?", FileHandleConstant.shcdqyctxt,
                FileHandleConstant.shcdqyctxtbak,3));
        fileConfigList.add(new FileConfig("43",FileHandleConstant.shcdqycehrule,
                "0 0 9 * * ?", FileHandleConstant.shcdqyceh,
                FileHandleConstant.shcdqycehbak,3));
        fileConfigList.add(new FileConfig("44",FileHandleConstant.shcdqsolarrbrule,
                "0 0 9 * * ?", FileHandleConstant.shcdqsolarrb,
                FileHandleConstant.shcdqsolarrbbak, 3));
        fileConfigList.add(new FileConfig("45",FileHandleConstant.shcdqwindrbrule,
                "0 0 9 * * ?", FileHandleConstant.shcdqwindrb,
                FileHandleConstant.shcdqwindrbbak,3));
//        fileConfigList.add(new FileConfig("46",FileHandleConstant.shcdqeflrule,
//                    "0 0 9 * * ?", FileHandleConstant.shcdqefl,
//                FileHandleConstant.shcdqeflbak,3));
        return fileConfigList;
    }


    /**
     * @Date 2024年3月13日08:47:14
     * @return List<FileConfig>  List<FileConfig>
     * @Author fxr
     */
    public static List<FileConfig> fileConfigList = new ArrayList<FileConfig>() {
        {
            System.out.println("11111111111");
//            //超短期
            add(new FileConfig("32", "SH_{yyyyMMddHHmm}_CDQXNYFORE.txt",
                    "0 0 9 * * ?", "/home/sprixin/shanghai/hdjhcRB/test/",
                    "/home/sprixin/shanghai/hd/cdq/d5000_cdqbak/", 3));
            add(new FileConfig("33", "SH_{yyyyMMddHHmm}_CDQXNYFORE.eh",
                    "0 0 9 * * ?", "/home/sprixin/shanghai/hdjhcRB/test/",
                    "/home/sprixin/shanghai/hd/cdq/d5000_cdqbak/", 3));
            add(new FileConfig("34", "SH_{yyyyMMddHHmm}_CDQXNYYC.eh",
                    "0 0 9 * * ?", "/home/sprixin/shanghai/hdjhcRB/test/",
                    "/home/sprixin/shanghai/hd/cdq/d5000_cdqbak/", 3));
            add(new FileConfig("35", "SH_{yyyyMMddHHmm}_CDQXNYYC.txt",
                    "0 0 9 * * ?", "/home/sprixin/shanghai/hdjhcRB/test/",
                    "/home/sprixin/shanghai/hd/cdq/d5000_cdqbak/", 3));
        }
    };


    @Override
    public void cdqGuaranteePlant(String date) throws Exception {
        InetAddress inetAddress = InetAddress.getLocalHost();
        log.info("inetAddressinetAddressinetAddress******" +  inetAddress);
        int serverPort = 9110;
        Boolean masterStatus = getAliveStatus(masterip, masterip, serverPort);
        System.out.println(masterStatus);
        int slaveServerPort = 9110;
        Boolean slaveStatus = getAliveStatus(slaveip, slaveip, slaveServerPort);
        System.out.println(slaveStatus);
        //获取静态内部类中状态中为1的数据---上午短期发送文件校验
        List<FileConfig> fileConfigs = getlist();
        List<FileConfig> nameParterns =
                fileConfigs.stream().filter(e -> e.getStatus() == 3).collect(Collectors.toList());
        if (masterStatus && inetAddress.getHostAddress().equals(masterip)) {
            System.out.println("走主机主机主机开始校验文件" + new Date());
            cdqHandlerFileLogic(date, nameParterns);
        } else {
            //从机处理
//        List<FileConfig> fileConfigs= fileConfigList;
//        List<FileConfig> nameParterns =
//                fileConfigs.stream().filter(e -> e.getStatus() == 3).collect(Collectors.toList());
            System.out.println("走从机从机从机开始校验文件" + new Date());
            cdqHandlerFileLogic(date, nameParterns);
        }
        log.info("结束结束结束结束结束结束******" +  date);
    }

    @Override
    public void test() {
        System.out.println("6666666666666");
    }


    /**
     * @param date date
     * @param nameParterns  content
     * @Date 2024年3月13日08:47:14
     * @Author fxr
     */
    private void cdqHandlerFileLogic(String date, List<FileConfig> nameParterns) {
        /**
         * 校验文件是否存在  result =true表示都在
         * 然后等着发送就好了，false表示不全在，要生成txt记录
         * 并保存在固定路径下
         * */
        Map<String, Object> map = handlerRules(date, nameParterns);
        Boolean result = Convert.toBool(map.get("result"));
        List<String> ids = new ArrayList<>();
        log.info("resultresultresultresult******" + result);
        if (!result) {
            log.info("111111111111111111111111");
            //没有文件的话，生成一个记录文件
            Map<String, String> stringMap = Convert.toMap(String.class, String.class, map.get("data"));
            String message = "";
            for (Map.Entry<String, String> string : stringMap.entrySet()) {
                message = message + string.getValue() + ",";
                String id = string.getKey();
                ids.add(id);
            }
            String fileName = "check_" + date.substring(0, 10).replaceAll("-", "") + ".txt";
            createTextFile(checkFilePath, fileName, message);
            //然后找之前的批次文件修改日期进行发送
            String lastDate = DateUtils.minuteAdd(date, -15, DateUtils.FORMAT_STR1);
            List<FileConfig> oldFileConfigs =
                    nameParterns.stream().filter(e -> ids.contains(e.getId())).collect(Collectors.toList());
            Map<String, String> oldMap = oldHandlerRules(lastDate, oldFileConfigs);
            log.info("oldMapoldMapoldMapoldMap******" + oldMap.size());
            for (Map.Entry<String, String> string : stringMap.entrySet()) {
                String newId = string.getKey();
                for (Map.Entry<String, String> old : oldMap.entrySet()) {
                    String id = old.getKey();
                    String name = old.getValue();
                    String newName = null;
                    FileConfig fileConfig =
                            nameParterns.stream().filter(e -> e.getId().equals(id)).findAny().get();
                    if (id.equals(newId)) {
                        newName = string.getValue();
                        String destPath = fileConfig.getFilePath();
                        String bakPath = fileConfig.getBakPath();
                        String oldName = null;
                        try {
                            byte[] bytes = name.getBytes("GBK");
                            oldName = new String(bytes, "GBK");
                        } catch (Exception e) {
                            log.info("eeeee******" + e);
                        }
                        log.info("namenamename******" + name);
                        log.info("oldNameoldNameoldName******" + oldName);
                        log.info("newNamenewName******" + newName);
                        //迁移昨天的文件并修改名称完成
                        FileUtil.copy(FileUtil.file(bakPath + oldName),
                                FileUtil.file(destPath + newName), true);
                        //进入文件内部，进行文件内时间的修改
                        //迁移昨天的文件并修改名称完成
                        log.info("22222******" + 22222);
                        cdqFileAnalysisTime(destPath, newName, oldName);
                    }
                }
            }
        }
    }

    /**
     * @param date         date
     * @param nameParterns content
     * @Date 2024年3月13日08:47:14
     * @Author fxr
     */
    private void handlerFileLogic(String date, List<FileConfig> nameParterns) {
        /**
         * 校验文件是否存在  result =true表示都在
         * 然后等着发送就好了，false表示不全在，要生成txt记录
         * 并保存在固定路径下
         * */
        log.info("开始进入逻辑处理******" +  nameParterns.size());
        Map<String, Object> map = handlerRules(date, nameParterns);
        log.info("开始进入逻辑处理******" +  map.size());
        Boolean result = Convert.toBool(map.get("result"));
        log.info("resultresultresultresult******" +  result);
        List<String> ids = new ArrayList<>();
        if (!result) {
            //没有文件的话，生成一个记录文件
            Map<String, String> stringMap = Convert.toMap(String.class, String.class, map.get("data"));
            String message = "";
            for (Map.Entry<String, String> string : stringMap.entrySet()) {
                message = message + string.getValue() + ",";
                String id = string.getKey();
                ids.add(id);
            }
            String fileName = "check_" + date.substring(0, 10).replaceAll("-", "") + ".txt";
            createTextFile(checkFilePath, fileName, message);
            log.info("messagemessagemessagemessage******" +  message);
            //然后找之前的批次文件修改日期进行发送
            String lastDate = DateUtils.dayAdd(date, -1, DateUtils.FORMAT_STR1);
            List<FileConfig> oldFileConfigs =
                    nameParterns.stream().filter(e -> ids.contains(e.getId())).collect(Collectors.toList());
            Map<String, String> oldMap = oldHandlerRules(lastDate, oldFileConfigs);
            log.info("oldMapoldMapoldMapoldMap******" +  oldMap.size());
            for (Map.Entry<String, String> string : stringMap.entrySet()) {
                String newId = string.getKey();
                for (Map.Entry<String, String> old : oldMap.entrySet()) {
                    String id = old.getKey();
                    String name = old.getValue();
                    String newName = null;
                    if (id.equals(newId)) {
                        newName = string.getValue();
                        FileConfig fileConfig =
                                nameParterns.stream().filter(e -> e.getId().equals(id)).findAny().get();
                        String destPath = fileConfig.getFilePath();
                        String bakPath = fileConfig.getBakPath();
                        String oldGbkName = null;
                        try {
                            byte[] bytes = name.getBytes("GBK");
                            oldGbkName = new String(bytes, "GBK");
                        } catch (Exception e) {
                            log.info("eeeee******" + e);
                        }
                        log.info("namenamename******" + name);
                        log.info("oldNameoldNameoldName******" + oldGbkName);
                        log.info("newNamenewName******" + newName);
                        //迁移昨天的文件并修改名称完成
                        log.info("22222******" + 22222);
                        FileUtil.copy(FileUtil.file(bakPath + oldGbkName),
                                FileUtil.file(destPath + newName), true);

                        //进入文件内部，进行文件内时间的修改
                        fileAnalysisTime(destPath, newName, oldGbkName);
                    }


                }
            }
        }
    }


    /**
     * @param destPath date
     * @param newName  content
     * @param oldName  content
     * @Date 2024年3月13日08:47:14
     * @Author fxr
     */
    private void cdqFileAnalysisTime(String destPath, String newName, String oldName) {
        log.info("开始进入解析生成新文件步骤********");
        Integer integer = cdqDetermine(newName);
        log.info("integerintegerintegerintegerinteger" + integer);
        switch (integer) {
            case 1:
                log.info(integer + "类型解析生成开始" + newName + "**" + destPath + "***" + oldName);
                readLineToChaneTimeForForeTxt(destPath, newName, oldName);
                log.info(integer + "类型解析生成完成" + newName + "**" + destPath + "***" + oldName);
                break;
            case 2:
                log.info(integer + "类型解析生成开始" + newName + "**" + destPath + "***" + oldName);
                readLineToChaneTimeForForeEh(destPath, newName, oldName);
                log.info(integer + "类型解析生成完成" + newName + "**" + destPath + "***" + oldName);
                break;
            case 3:
                log.info(integer + "类型解析生成完成" + newName + "**" + destPath + "***" + oldName);
                readLineToChaneTimeForYcTxt(destPath, newName, oldName);
                log.info(integer + "类型解析生成完成" + newName + "**" + destPath + "***" + oldName);
                break;
            case 4:
                log.info(integer + "类型解析生成完成" + newName + "**" + destPath + "***" + oldName);
                readLineToChaneTimeForForeEh(destPath, newName, oldName);
                log.info(integer + "类型解析生成完成" + newName + "**" + destPath + "***" + oldName);
                break;
            default:
                break;
        }
    }


    /**
     * @param destPath content
     * @param newName  content
     * @param oldName  content
     * @Date 2024年3月13日08:47:14
     * @Author fxr
     */
    private void readLineToChaneTimeForForeTxt(String destPath, String newName, String oldName) {
        StringBuilder stringBuilder = new StringBuilder();
        int cnt = 0;
        int rowLine = 0;
        String oldYearMonDay = oldName.substring(3, 11);
        String newYearMonDay = newName.substring(3, 11);
        String year = newName.substring(3, 7);
        String month = newName.substring(7, 9);
        String day = newName.substring(9, 11);
        String hour = newName.substring(11, 13);
        String min = newName.substring(13, 15);
        String newDate = year + "-" + month + "-" + day
                + " " + hour + ":" + min + ":" + "00";
        String enter = System.getProperty("line.separator");
        //新第一行的时间
        String date = DateUtil.minuteAdd(newDate, -15, DateUtil.FORMAT_STR1);
        //老第一行的时间
        String oldDate = DateUtil.minuteAdd(date, -15, DateUtil.FORMAT_STR1);
        String oldLineOne = "dataTime='" + oldDate + "'";
        String newLineOne = "dataTime='" + date + "'";
        //新文件内容的时间
        String filedate = year + "-" + month + "-" + day + "_" + hour + ":" + min;
        //老文件内容的时间
        String oldFileDate = date.substring(0, 16).replaceAll(" ", "_");
        String plantTime = "planDate='" + oldYearMonDay + "'";
        String newTime = "planDate='" + newYearMonDay + "'";
        try {
            FileInputStream fileInputStream = new FileInputStream(destPath + newName);
            InputStreamReader inputStreamReader = new InputStreamReader(fileInputStream, "GBK");
            BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
            String line;
            while ((line = bufferedReader.readLine()) != null) {
                rowLine++;
                if (line.contains(oldLineOne)) {
                    line = line.replace(oldLineOne, newLineOne);
                    cnt++;
                }
                if (line.contains(plantTime)) {
                    line = line.replace(plantTime, newTime);
                    cnt++;
                }
                if (line.contains(oldFileDate)) {
                    line = line.replace(oldFileDate, filedate);
                    cnt++;
                }
                if (rowLine == 1) {
                    stringBuilder.append(line);
                } else {
                    stringBuilder.append(enter).append(line);
                }
            }
            FileUtils.writeStringToFile(new File(destPath + newName), stringBuilder.toString(), "GBK");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * @param destPath content
     * @param newName  content
     * @param oldName  content
     * @Date 2024年3月13日08:47:14
     * @Author fxr
     */
    private void readLineToChaneTimeForYcTxt(String destPath, String newName, String oldName) {
        StringBuilder stringBuilder = new StringBuilder();
        int cnt = 0;
        int rowLine = 0;
        String oldYearMonDay = oldName.substring(3, 11);
        String newYearMonDay = newName.substring(3, 11);
        String year = newName.substring(3, 7);
        String month = newName.substring(7, 9);
        String day = newName.substring(9, 11);
        String hour = newName.substring(11, 13);
        String min = newName.substring(13, 15);
        String newDate = year + "-" + month + "-" + day
                + " " + hour + ":" + min + ":" + "00";
        String enter = System.getProperty("line.separator");
        //新第一行的时间
        String date = DateUtil.minuteAdd(newDate, -15, DateUtil.FORMAT_STR1);
        //老第一行的时间
        String oldDate = DateUtil.minuteAdd(date, -15, DateUtil.FORMAT_STR1);
        String oldLineOne = "dataTime='" + oldDate + "'";
        String newLineOne = "dataTime='" + date + "'";
        //新文件内容的时间
        String plantTime = "planDate='" + oldYearMonDay + "'";
        String newTime = "planDate='" + newYearMonDay + "'";
        try {
            FileInputStream fileInputStream = new FileInputStream(destPath + newName);
            InputStreamReader inputStreamReader = new InputStreamReader(fileInputStream, "GBK");
            BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
            String line;
            while ((line = bufferedReader.readLine()) != null) {
                rowLine++;
                if (line.contains(oldLineOne)) {
                    line = line.replace(oldLineOne, newLineOne);
                    cnt++;
                }
                if (line.contains(plantTime)) {
                    line = line.replace(plantTime, newTime);
                    cnt++;
                }
                if (rowLine == 1) {
                    stringBuilder.append(line);
                } else {
                    stringBuilder.append(enter).append(line);
                }
            }
            FileUtils.writeStringToFile(new File(destPath + newName), stringBuilder.toString(), "GBK");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * @param destPath content
     * @param newName  content
     * @param oldName  content
     * @Date 2024年3月13日08:47:14
     * @Author fxr
     */
    private void readLineToChaneTimeForBalanceTxt(String destPath, String newName, String oldName) {
        StringBuilder stringBuilder = new StringBuilder();
        int cnt = 0;
        int rowLine = 0;
        String year = newName.substring(3, 7);
        String month = newName.substring(7, 9);
        String day = newName.substring(9, 11);
        String newDate = year + "-" + month + "-" + day;
        String enter = System.getProperty("line.separator");
        //新第一行的时间
        String date = DateUtil.dayAdd(newDate, -1, DateUtil.FORMAT_STR3);
        String oldDate = DateUtil.dayAdd(newDate, -2, DateUtil.FORMAT_STR3);
        //老第一行的时间
        String oldLineOne = "dataTime='" + oldDate;
        String newLineOne = "dataTime='" + date;
        String plantTime = "planDate='" + oldName.substring(3,11) + "'";
        String newTime = "planDate='" + newName.substring(3,11) + "'";
        try {
            FileInputStream fileInputStream = new FileInputStream(destPath + newName);
            InputStreamReader inputStreamReader = new InputStreamReader(fileInputStream, "GBK");
            BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
            String line;
            while ((line = bufferedReader.readLine()) != null) {
                rowLine++;
                if (line.contains(oldLineOne)) {
                    line = line.replace(oldLineOne, newLineOne);
                    cnt++;
                }
                if (line.contains(plantTime)) {
                    line = line.replace(plantTime, newTime);
                    cnt++;
                }
                if (rowLine == 1) {
                    stringBuilder.append(line);
                } else {
                    stringBuilder.append(enter).append(line);
                }
            }
            FileUtils.writeStringToFile(new File(destPath + newName), stringBuilder.toString(), "GBK");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    /**
     * @param destPath content
     * @param newName  content
     * @param oldName  content
     * @Date 2024年3月13日08:47:14
     * @Author fxr
     */
    private void readLineToChaneTimeForBalanceEh(String destPath, String newName, String oldName) {
        StringBuilder stringBuilder = new StringBuilder();
        int cnt = 0;
        int rowLine = 0;
        String year = newName.substring(3, 7);
        String month = newName.substring(7, 9);
        String day = newName.substring(9, 11);
        String newDate = year + "-" + month + "-" + day;
        String enter = System.getProperty("line.separator");
        //新第一行的时间
        String date = DateUtil.dayAdd(newDate, -1, DateUtil.FORMAT_STR3);
        //老第一行的时间
        String oldDate = DateUtil.dayAdd(date, -1, DateUtil.FORMAT_STR3);
        String oldLineOne = "time='" + oldDate;
        String newLineOne = "time='" + date;
        try {
            FileInputStream fileInputStream = new FileInputStream(destPath + newName);
            InputStreamReader inputStreamReader = new InputStreamReader(fileInputStream, "GBK");
            BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
            String line;
            while ((line = bufferedReader.readLine()) != null) {
                rowLine++;
                if (line.contains(oldLineOne)) {
                    line = line.replace(oldLineOne, newLineOne);
                    cnt++;
                }
                if (line.contains(oldName)) {
                    line = line.replace(oldName, newName);
                    cnt++;
                }
                if (line.contains(oldName.substring(0, 15))) {
                    line = line.replace(oldName.substring(0, 15), newName.substring(0, 15));
                    cnt++;
                }
                if (rowLine == 1) {
                    stringBuilder.append(line);
                } else {
                    stringBuilder.append(enter).append(line);
                }
            }
            FileUtils.writeStringToFile(new File(destPath + newName), stringBuilder.toString(), "GBK");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }




    /**
     * @param destPath content
     * @param newName  content
     * @param oldName  content
     * @Date 2024年3月13日08:47:14
     * @Author fxr
     */
    private void readLineToChaneTimeForForeEh(String destPath, String newName, String oldName) {
        StringBuilder stringBuilder = new StringBuilder();
        int cnt = 0;
        int rowLine = 0;
        String year = newName.substring(3, 7);
        String month = newName.substring(7, 9);
        String day = newName.substring(9, 11);
        String hour = newName.substring(11, 13);
        String min = newName.substring(13, 15);
        String newDate = year + "-" + month + "-" + day
                + " " + hour + ":" + min + ":" + "00";
        String enter = System.getProperty("line.separator");
        //新第一行的时间
        String date = DateUtil.minuteAdd(newDate, -15, DateUtil.FORMAT_STR1);
        //老第一行的时间
        String oldDate = DateUtil.minuteAdd(date, -15, DateUtil.FORMAT_STR1);
        String oldLineOne = "time='" + oldDate + "'";
        String newLineOne = "time='" + date + "'";
        try {
            FileInputStream fileInputStream = new FileInputStream(destPath + newName);
            InputStreamReader inputStreamReader = new InputStreamReader(fileInputStream, "GBK");
            BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
            String line;
            while ((line = bufferedReader.readLine()) != null) {
                rowLine++;
                if (line.contains(oldLineOne)) {
                    line = line.replace(oldLineOne, newLineOne);
                    cnt++;
                }
                if (line.contains(oldName.substring(0, 15))) {
                    line = line.replace(oldName.substring(0, 15), newName.substring(0, 15));
                    cnt++;
                }
                if (rowLine == 1) {
                    stringBuilder.append(line);
                } else {
                    stringBuilder.append(enter).append(line);
                }
            }
            FileUtils.writeStringToFile(new File(destPath + newName), stringBuilder.toString(), "GBK");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * @param newName content
     * @Date 2024年3月13日08:47:14
     * @Author fxr
     * @return  Integer Integer
     */
    private Integer cdqDetermine(String newName) {
        if (newName.startsWith("SH_20") && newName.contains("CDQXNYFORE") && newName.endsWith(".txt")) {
            return 1;
        } else if (newName.startsWith("SH_20") && newName.contains("CDQXNYFORE") && newName.endsWith(".eh")) {
            return 2;
        } else if (newName.startsWith("SH_20") && newName.contains("CDQXNYYC") && newName.endsWith(".txt")) {
            return 3;
        } else if ((newName.startsWith("SH_20") && newName.contains("CDQXNYYC") && newName.endsWith(".eh"))) {
            return 4;
        }
        return 5;
    }

    /**
     * @param newName content
     * @Date 2024年3月13日08:47:14
     * @Author fxr
     * @return  Integer Integer
     */
    private Integer dqDetermine(String newName) {
        if (newName.startsWith("SH_20") && newName.contains("XNYBLANCERQYC") && newName.endsWith(".txt")) {
            return 1;
        } else if (newName.startsWith("SH_20") && newName.contains("XNYBLANCERQYC") && newName.endsWith(".eh")) {
            return 2;
        } else if (newName.startsWith("sh") && newName.endsWith(".xml")) {
            return 3;
        } else if ((newName.startsWith("上海") && !newName.contains("短期") && newName.endsWith(".RB"))) {
            return 4;
        } else if ((newName.startsWith("上海") && !newName.contains("短期") && newName.endsWith(".eh"))) {
            return 5;
        }
        return 6;
    }


    /**
     * @param destPath date
     * @param newName  content
     * @param oldName  content
     * @Date 2024年3月13日08:47:14
     * @Author fxr
     */
    private void fileAnalysisTime(String destPath, String newName, String oldName) {
        log.info("destPath******" + destPath + "----" + newName + "+++++++++" + oldName);
        Integer integer = dqDetermine(newName);
        log.info("dqDeterminedqDeterminedqDetermine" + integer);
        switch (integer) {
            case 1:
                readLineToChaneTimeForBalanceTxt(destPath, newName, oldName);
                break;
            case 2:
                readLineToChaneTimeForBalanceEh(destPath, newName, oldName);
                break;
            case 3:
                readLineToChaneTimeForXml(destPath, newName, oldName);
                break;
            case 4:
                readLineToChaneTimeForRb(destPath, newName, oldName);
                break;
            case 5:
                readLineToChaneTimeForRbEh(destPath, newName, oldName);
                break;
            default:
                break;
        }
    }


    /**
     * @param destPath content
     * @param newName  content
     * @param oldName  content
     * @Date 2024年3月13日08:47:14
     * @Author fxr
     */
    private void readLineToChaneTimeForXml(String destPath, String newName, String oldName) {
        StringBuilder stringBuilder = new StringBuilder();
        int cnt = 0;
        int rowLine = 0;
        String enter = System.getProperty("line.separator");
        try {
            FileInputStream fileInputStream = new FileInputStream(destPath + newName);
            InputStreamReader inputStreamReader = new InputStreamReader(fileInputStream, "GBK");
            BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
            String line;
            while ((line = bufferedReader.readLine()) != null) {
                rowLine++;
                if (line.contains("sysTimeMax=")) {
                    String sysTimeMaxTime = line.substring(line.length() - 21, line.length() - 11);
                    String newSysTimeMaxTime = DateUtil.dayAdd(sysTimeMaxTime, 1, DateUtil.FORMAT_STR3);
                    line = line.replace(sysTimeMaxTime, newSysTimeMaxTime);
                    cnt++;
                }
                if (line.contains("date=") && line.contains("datetime=")) {
                    Integer startIndex = line.indexOf("date=");
                    Integer middleIndex = line.indexOf("datetime=");
                    Integer endIndex = line.indexOf("powervalue=");
                    String dateStr = line.substring(startIndex + 6, middleIndex - 2);
                    String oldDate = dateStr;
                    String replaDate = DateUtil.dayAdd(dateStr, 1, DateUtil.FORMAT_STR3);
                    String newDate = replaDate;
                    line = line.replace(oldDate, newDate);
                    String dateTimeStr = line.substring(middleIndex + 10, endIndex - 11);
                    String oldDateTime = dateTimeStr + " ";
                    String replaDateTime = DateUtil.dayAdd(oldDateTime, 1, DateUtil.FORMAT_STR3);
                    String newDateTime = replaDateTime + " ";
                    line = line.replace(oldDateTime, newDateTime);
                }
                if (rowLine == 1) {
                    stringBuilder.append(line);
                } else {
                    stringBuilder.append(enter).append(line);
                }
            }
            FileUtils.writeStringToFile(new File(destPath + newName), stringBuilder.toString(), "GBK");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * @param destPath content
     * @param newName  content
     * @param oldName  content
     * @Date 2024年3月13日08:47:14
     * @Author fxr
     */
    private void readLineToChaneTimeForRbEh(String destPath, String newName, String oldName) {
        StringBuilder stringBuilder = new StringBuilder();
        int cnt = 0;
        int rowLine = 0;
        String time = newName.substring(newName.length() - 11, newName.length() - 3);
        String year = time.substring(0, 4);
        String month = time.substring(4, 6);
        String day = time.substring(6, 8);
        String enter = System.getProperty("line.separator");
        //新第一行的时间
        String newDate = year + "-" + month + "-" + day;
        //老第一行的时间
        String oldDate = DateUtil.dayAdd(newDate, -1, DateUtil.FORMAT_STR3);
        String oldLineOne = "time='" + oldDate;
        String newLineOne = "time='" + newDate;
        try {
            FileInputStream fileInputStream = new FileInputStream(destPath + newName);
            InputStreamReader inputStreamReader = new InputStreamReader(fileInputStream, "GBK");
            BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
            String line;
            while ((line = bufferedReader.readLine()) != null) {
                rowLine++;
                if (line.contains(oldLineOne)) {
                    line = line.replace(oldLineOne, newLineOne);
                    cnt++;
                }
                if (line.contains(oldName)) {
                    line = line.replace(oldName, newName);
                    cnt++;
                }
                if (line.contains(oldName.substring(0, oldName.length() - 3) + "-")) {
                    String oldData = line.substring(line.length() - 21, line.length() - 4);
                    String[] oldTimeData = oldData.split("-");
                    String start = oldTimeData[0];
                    String end = oldTimeData[1];
                    String startTime = start.substring(0, 4)
                            + "-" + start.substring(4, 6) + "-" + start.substring(6, 8);
                    String newStartDate = DateUtil.dayAdd(startTime, 1, DateUtil.FORMAT_STR3);
                    String endTime = end.substring(0, 4)
                            + "-" + end.substring(4, 6) + "-" + end.substring(6, 8);
                    String newEndDate = DateUtil.dayAdd(endTime, 1, DateUtil.FORMAT_STR3);
                    line = line.replace(start, newStartDate.replaceAll("-", ""));
                    line = line.replace(end, newEndDate.replaceAll("-", ""));
                    cnt++;
                }
                if (rowLine == 1) {
                    stringBuilder.append(line);
                } else {
                    stringBuilder.append(enter).append(line);
                }
            }
            FileUtils.writeStringToFile(new File(destPath + newName), stringBuilder.toString(), "GBK");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * @param destPath content
     * @param newName  content
     * @param oldName  content
     * @Date 2024年3月13日08:47:14
     * @Author fxr
     */
    private void readLineToChaneTimeForRb(String destPath, String newName, String oldName) {
        StringBuilder stringBuilder = new StringBuilder();
        int cnt = 0;
        int rowLine = 0;
        String dateRegex = "^(1[6-9]|[2-9]\\d)\\d{2}-(0?[1-9]|1[0-2])-(0?[1-9]|[12]\\d|3[01])$";
        String enter = System.getProperty("line.separator");
        try {
            FileInputStream fileInputStream = new FileInputStream(destPath + newName);
            InputStreamReader inputStreamReader = new InputStreamReader(fileInputStream, "GBK");
            BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
            String line;
            while ((line = bufferedReader.readLine()) != null) {
                rowLine++;
                if (line.contains("date=")) {
                    String[] strings = line.split("'");
                    String date = strings[1];
                    boolean isValid = date.matches(dateRegex);
                    String newDate = DateUtil.dayAdd(date, 1, DateUtil.FORMAT_STR3);
                    if (isValid) {
                        line = line.replace(date, newDate);
                        cnt++;
                    }
                }
                if (rowLine == 1) {
                    stringBuilder.append(line);
                } else {
                    stringBuilder.append(enter).append(line);
                }
            }
            FileUtils.writeStringToFile(new File(destPath + newName), stringBuilder.toString(), "GBK");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * @param directoryPath date
     * @param fileName      nameParterns
     * @param content       content
     * @Date 2024年3月13日08:47:14
     * @Author fxr
     */
    private void createTextFile(String directoryPath, String fileName, String content) {
        File directory = new File(directoryPath);
        if (!directory.exists()) {
            directory.mkdirs(); // 创建目录
        }
        try (BufferedWriter writer =
                     new BufferedWriter(new FileWriter(directoryPath + File.separator + fileName))) {
            writer.write(content); // 写入内容
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * @param date         date
     * @param nameParterns nameParterns
     * @return Boolean
     * @Date 2024年3月13日08:47:14
     * @Author fxr
     */
    private Map<String, Object> handlerRules(String date, List<FileConfig> nameParterns) {
        boolean flag = true;
        Map<String, String> hashMap = new HashMap<>();
        for (FileConfig fileData : nameParterns) {
            log.info("fileDatafileData******" + fileData.toString());
            File file = new File(fileData.getBakPath());
            log.info("filefilefile******" + file.getName());
            log.info("filefilefile******" + file.getPath());
            String id = fileData.getId();
            String nameExpression = fileData.getFileNameRules();
            String[] parterns = this.extract(nameExpression);
            String fileName1 = fileData.getFileNameRules();
            log.info("fileName1*****************" + fileName1);
            if (parterns.length > 0) {
                for (int i = 0; i < parterns.length; i++) {
                    String partern = parterns[i];
                    String tmpPartern = partern.replace("{", "").replace("}", "");
                    if (i == 0) {
                        if (partern.contains("+")) {
                            String[] strs = partern.split("\\+");
                            //获取第二个值
                            int min = Integer.valueOf(strs[1]);
                            String timeStr1 = DateUtils.minuteAdd(date, min, DateUtils.FORMAT_STR1);
                            timeStr1 = DateUtils.dateFormat(timeStr1, DateUtils.FORMAT_STR1, strs[0]);
                            fileName1 = fileName1.replace("{" + partern + "}", timeStr1);
                            log.info(fileName1);
                        } else {
                            String timrStr = DateUtils.dateFormat(date, DateUtils.FORMAT_STR1, tmpPartern);
                            fileName1 = nameExpression.replace("{" + partern + "}", timrStr);
                        }
                    } else {
                        //表示文件名称中是一个时间范围
                        if (partern.contains("+") || partern.contains("-")) {
                            //表示后续时间点与前第一个时间点有对应关系
                            String timeStr1 = "";
                            if (partern.contains("+")) {
                                String[] strs = partern.split("\\+");
                                //获取第二个值
                                int min = Integer.valueOf(strs[1]);
                                timeStr1 = DateUtils.minuteAdd(date, min, DateUtils.FORMAT_STR1);
                                timeStr1 = DateUtils.dateFormat(timeStr1, DateUtils.FORMAT_STR1, strs[0]);
                            } else {
                                String[] strs = partern.split("-");
                                int min = Integer.valueOf(strs[1]);
                                timeStr1 = DateUtils.minuteAdd(date, min * (-1), DateUtils.FORMAT_STR1);
                                timeStr1 = DateUtils.dateFormat(timeStr1, DateUtils.FORMAT_STR1, strs[0]);
                            }
                            fileName1 = fileName1.replace("{" + partern + "}", timeStr1);
                        }
                    }
                    log.info("newnewnewnewnewnewnewnfileName1*****************" + fileName1);
                }
            }

            //获取所有文件
            Collection<File> files = FileUtils.listFiles(file.getAbsoluteFile(), null, false);
            log.info("filesfilesfilesfilesfiles******" + files.size());
            if (CollectionUtils.isEmpty(files)) {
                hashMap.put(id, fileName1);
                flag = false;
            } else {
                List<String> fileStrings = new ArrayList<>();
                for (File f : files) {
                    String fileName2 = f.getName();
                    fileStrings.add(fileName2);
                }
                if (CollectionUtil.isNotEmpty(fileStrings)) {
                    if (!fileStrings.contains(fileName1)) {
                        hashMap.put(id, fileName1);
                        //表示该文件在此目录
                        flag = false;
                    }
                }
            }
            log.info("flagflagflagflagflag*****************" + flag);
        }

        Map<String, Object> map = new HashMap<>();
        map.put("result", flag);
        map.put("data", hashMap);
        return map;
    }

    /**
     * @param date         date
     * @param nameParterns nameParterns
     * @return Boolean
     * @Date 2024年3月13日08:47:14
     * @Author fxr
     */
    private Map<String, String> oldHandlerRules(String date, List<FileConfig> nameParterns) {
        Map<String, String> hashMap = new HashMap<>();
        for (FileConfig fileData : nameParterns) {
            String id = fileData.getId();
            String nameExpression = fileData.getFileNameRules();
            String[] parterns = this.extract(nameExpression);
            String fileName1 = fileData.getFileNameRules();
            if (parterns.length > 0) {
                for (int i = 0; i < parterns.length; i++) {
                    String partern = parterns[i];
                    String tmpPartern = partern.replace("{", "").replace("}", "");
                    if (i == 0) {
                        if (partern.contains("+")) {
                            String[] strs = partern.split("\\+");
                            //获取第二个值
                            int min = Integer.valueOf(strs[1]);
                            String timeStr1 = DateUtils.minuteAdd(date, min, DateUtils.FORMAT_STR1);
                            timeStr1 = DateUtils.dateFormat(timeStr1, DateUtils.FORMAT_STR1, strs[0]);
                            fileName1 = fileName1.replace("{" + partern + "}", timeStr1);
                            log.info(fileName1);
                        } else {
                            String timrStr = DateUtils.dateFormat(date, DateUtils.FORMAT_STR1, tmpPartern);
                            fileName1 = nameExpression.replace("{" + partern + "}", timrStr);
                        }
                    } else {
                        //表示文件名称中是一个时间范围
                        if (partern.contains("+") || partern.contains("-")) {
                            //表示后续时间点与前第一个时间点有对应关系
                            String timeStr1 = "";
                            if (partern.contains("+")) {
                                String[] strs = partern.split("\\+");
                                //获取第二个值
                                int min = Integer.valueOf(strs[1]);
                                timeStr1 = DateUtils.minuteAdd(date, min, DateUtils.FORMAT_STR1);
                                timeStr1 = DateUtils.dateFormat(timeStr1, DateUtils.FORMAT_STR1, strs[0]);
                            } else {
                                String[] strs = partern.split("-");
                                int min = Integer.valueOf(strs[1]);
                                timeStr1 = DateUtils.minuteAdd(date, min * (-1), DateUtils.FORMAT_STR1);
                                timeStr1 = DateUtils.dateFormat(timeStr1, DateUtils.FORMAT_STR1, strs[0]);
                            }
                            fileName1 = fileName1.replace("{" + partern + "}", timeStr1);
                        }
                    }
                }
            }
            log.info("oldoldoldoldoldfiname******" + fileName1);
            hashMap.put(id, fileName1);
        }
        return hashMap;
    }

    /**
     * @param mechingeHost mechingeHost
     * @param serverHost   serverHost
     * @param serverPort   serverPort
     * @return Boolean
     * @Date 2024年3月13日08:47:14
     * @Author fxr
     */
    private Boolean getAliveStatus(String mechingeHost, String serverHost, int serverPort) {
        //获取传输新主机的服务器存活状态
        Boolean mechingeFalg = getMechingeStaus(mechingeHost);
        log.info("mechingeFalgmechingeFalgmechingeFalg******" +  mechingeFalg);
        //获取传输新主机的服务存活状态
        Boolean serverFlag = getServerStatus(serverHost, serverPort);
        log.info("serverFlagserverFlag******" +  serverFlag);
        //根据判断，进行确认双主系统谁来执行此次任务
        if (mechingeFalg && serverFlag) {
            return true;
        } else {
            return false;
        }
    }


    /**
     * @param mechingeHost mechingeHost
     * @return Boolean
     */
    private Boolean getMechingeStaus(String mechingeHost) {
        log.info("exitCodeexitCodeexitCodeexitCode---" +  mechingeHost);
        try {
//            String command = "ping " + "10.10.10.117";
//            log.info("commandcommandcommand---" +  command);
//            Process process = Runtime.getRuntime().exec(command);
//            log.info("processprocessprocess---" +  process);
//            int exitCode = process.waitFor();
//            log.info("exitCodeexitCode******" +  exitCode);
//            if (exitCode == 0) {
//                return true;
//            }
            Process p = Runtime.getRuntime().exec(new String[]{"ping", "-c", "4", mechingeHost});
            BufferedReader input = new BufferedReader(new InputStreamReader(p.getInputStream()));
            String line;
            while ((line = input.readLine()) != null) {
                if (line.contains("Unreachable")) {
                    // 如果输出包含"Unreachable"，说明ping不通
                    log.info("falsefalsefalsefalse******" +  false);
                    return false;
                } else if (line.contains("ttl=")) {
                    // 如果输出包含"ttl="，说明ping通了
                    log.info("truetruetruetrue******" +  true);
                    return true;
                }
            }
            input.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }

    /**
     * @param serverHost serverHost
     * @param serverPort serverPort
     * @return Boolean
     */
    private Boolean getServerStatus(String serverHost, int serverPort) {
//        int timeOut = 5000;
        Boolean flag = false;
        try {
//            Socket scoket = new Socket();
//            scoket.connect(new InetSocketAddress(serverHost, serverPort), timeOut);
//            flag = scoket.isBound();
//            log.info("flagflagflagflag******" +  flag);
//            scoket.close();
            String serviceName = "guarantee"; // 替换为你需要检查的服务名
            String command = "jps -l";
            // 执行命令
            Process process = Runtime.getRuntime().exec(command);
            // 读取命令执行结果
            BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()));
            String line;
            while ((line = reader.readLine()) != null) {
                log.info("linelinelineline******" + line);
                if (line.contains(serviceName)) {
                    flag = true;
                }
            }
            reader.close();
            // 等待命令执行完成
            process.waitFor();
            return flag;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }


    /**
     * sdfs
     *
     * @param inputString sdf
     * @return sdf
     */
    public String[] extract(String inputString) {
        Pattern pattern = Pattern.compile("\\{(.+?)\\}");
        Matcher matcher = pattern.matcher(inputString);
        int count = 0;
        while (matcher.find()) {
            count++;
        }
        String[] result = new String[count];
        matcher.reset();
        int index = 0;
        while (matcher.find()) {
            result[index++] = matcher.group(1);
        }
        return result;
    }

    /**
     * 创建文件
     *
     * @param time     时间
     * @param infoList 告警信息
     * @throws IOException 异常
     */
    private void createFile(String time, List<ReportAlarmInfo> infoList) throws IOException {
        String alarmFilePath = path;
        String phones = phone;
        phones = phones.substring(0, phones.length() - 1);
        log.info("phonesphonesphonesphones******" + phones);
        String fileName = "XNMS_" + DateUtils.dateFormat(time, DateUtils.FORMAT_STR1, "MMddHHmmss") + "_YX.txt";
        String context = "<检修公司 phone='" + phones + "'></检修公司>\r\n";
        for (ReportAlarmInfo info : infoList) {
            String alarmTime = info.getAlarmTime();
            String alarmInfo = info.getAlarmInfo();
            context += alarmTime + " " + alarmInfo + "\r\n";
        }
        FileUtils.write(new File(alarmFilePath + File.separator + fileName), context, "GBK");
    }





}